<?php
namespace app\model;

use think\Model;

use think\facade\Db;

class CustomerGroupModel extends Model
{

    protected $name = 'sh_customer_group';

    public static function get_list( $filter ){

        // global $_W;
        $uniacid = current_uni_account();
        $where_arr = [];
        $where_arr[] = ' cg.uniacid=' . $uniacid;
        if( !empty($filter['name']) ){
            $where_arr[] = ' cg.name like "%' . $filter['name'] . '%"';
        }

        $where_str = '';
        if( !empty( $where_arr ) ){
            $where_str = ' where ' . join(' and ', $where_arr );
        }

        $sql = 'select * from sh_customer_group cg ' . $where_str;

        // return pdo_fetchall( $sql );

        return Db::query( $sql );
    }

    public static function single( $customer_group_id ){

        $sql = 'select * from sh_customer_group where id=' . $customer_group_id;

        // return pdo_fetch( $sql );
        return Db::query( $sql )[0];
    }

    public static function edit( $id, $data ){

        $sql = 'update sh_customer_group set '.
        ' `name`="' . $data['name'] . '",'.
        ' `description`="' . $data['description'] . '",'.
        ' `sort_order`=' . $data['sort_order'] . ','.
        ' `is_default`=' . $data['is_default'] .
        ' where id=' . $id
        ;
//        echo $sql;
        // return pdo_query( $sql );
        return Db::execute( $sql );
    }

    // public static function create( $data ){
    public static function add( $data ){

        // global $_W;
        $uniacid = current_uni_account();
        $sql = 'insert into sh_customer_group set '.
            '`name`="' . $data['name'] . '",'.
            '`uniacid`="' . $uniacid . '",'.
            '`description`="' . $data['description'] . '",'.
            '`sort_order`="' . $data['sort_order'] . '",'.
            '`is_default`=' . $data['is_default']
        ;

//        echo $sql;
        // pdo_query( $sql );
        Db::execute( $sql );

        // return pdo_insertid( );
        return Db::name('sh_customer_group')->getLastInsID();
    }

    public static function setAllNotDefault(){

        $uniacid = current_uni_account();

        $sql = 'update sh_customer_group set '.
            '`is_default`=0' . 
            ' where `uniacid`=' . $uniacid 

        ;
         return Db::execute( $sql );

    }

}